﻿

namespace RolePlayingGame
{
    using System;
    class NameEnter
    {
        public static void EnterName()
        {
            string value = "Enter your name:";
            Console.ForegroundColor = ConsoleColor.White;
            int widthHalf = (Console.WindowWidth / 2) - (value.Length / 2);
            Console.SetCursorPosition(widthHalf, 10);
            Console.Write(value);
            string dashes = new string('-', 20);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.SetCursorPosition(widthHalf - 2, 11);
            Console.WriteLine(dashes);
            Console.SetCursorPosition(widthHalf - 2, 13);
            Console.WriteLine(dashes);
            Console.ResetColor();
            Console.SetCursorPosition(widthHalf, 12);
            string playerName = string.Empty;
            while (string.IsNullOrEmpty(playerName))
            {
                try
                {
                    playerName = ReadLimited(15);
                    if (string.IsNullOrEmpty(playerName))
                    {
                        throw new InvalidInputException("Name cannot be null");
                    }
                }
                catch (InvalidInputException)
                {
                    Console.SetCursorPosition(widthHalf - 7, 15);
                    Console.WriteLine("Name cannot be null! Try again.");
                    Console.SetCursorPosition(widthHalf, 12);
                }
                Console.ResetColor();
            }
        }
        private static string ReadLimited(int limit)
        {
            string str = string.Empty;
            while (true)
            {
                char c = Console.ReadKey(true).KeyChar;
                if (c == '\r')
                    break;
                if (c == '\b')
                {
                    if (str != "")
                    {
                        str = str.Substring(0, str.Length - 1);
                        Console.Write("\b \b");
                    }
                }
                else if (str.Length < limit)
                {
                    Console.Write(c);
                    str += c;
                }
            }
            return str;
        }
    }
}
